<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/10/11
 * Time: 16:59
 */

namespace app\api\service;

use \app\api\model\ThirdApp as ThirdAppModel;
use app\api\model\WebSubelement;
use app\api\model\WorkUser;
use app\common\lib\Redis;
use app\lib\exception\TokenException;
use app\lib\exception\UserException;
use \app\api\model\Work;
use think\Cache;
use think\Config;

class ThirdApp
{
    /**
     * 获取应用信息
     * @param $t_id
     * @return array|false|mixed|\PDOStatement|string|\think\Model
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAppInfo($t_id){
        Redis::getInstance()->get(9,'appinfo:t_id:'.$t_id);
        if (!empty($userInfo)){
            return json_decode($userInfo);
        }
        $userInfo = ThirdAppModel::getAppInfo($t_id);
        Redis::getInstance()->set(9,'appinfo:t_id:'.$t_id,json_encode($userInfo->toArray()),48*3600);
        return $userInfo;
    }

    /**
     * 修改用户列表
     * @param $t_id
     * @param $oldPassword
     * @param $newPassword
     * @return ThirdAppModel
     * @throws TokenException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function changePassword($t_id,$oldPassword,$newPassword){
        $userInfo = ThirdAppModel::getUserInfoByUserId($t_id);
        if (md5($oldPassword) != $userInfo->app_secret){
            throw new TokenException([
                'code'=>203,
                'msg'=>'密码错误',
                'error_code'=>26018
            ]);
        }
        $data['app_secret'] = md5($newPassword);
        $result =  ThirdAppModel::updateUserInfo($t_id,$data);
        return $result;
    }


    /**
     * 获取用户授权信息
     * @param $uid
     * @return array
     * @throws UserException
     */
    public function getAuthInfo($uid){
        $auth_arr = [
            'mini'=>0,
            'contact'=>0,
            'ai'=>0,
            'boss'=>0
        ];
        $userInfo = ThirdAppModel::getUserInfoByUserId($uid);
        if (!$userInfo){
            throw new UserException();
        }
        if ($userInfo->mini_id != 0 ){
            $auth_arr['mini'] = 1;
        }
        if ($userInfo->w_id != 0 ){
            $agentInfo = $this->getAgent($userInfo->w_id);
            if (!empty($agentInfo)){
                $agentInfo = $agentInfo->toArray();
                if ($agentInfo['agents'] != null){
                    $agents = $this->getAppType($agentInfo['agents'] );
                    if (!empty($agents)){
                        foreach ($agents as $k=>$v){
                            $auth_arr[$v] = 1;
                        }
                    }
                }
            }
        }
        return $auth_arr;
    }

    /**
     * 名片统计信息
     * @param $uid
     * @return array
     */
    public function getWorkUserInfo($uid){
        //员工数量
        $workNum = ThirdAppModel::getWorkUserNum($uid);
        //可以开通名片数量
        $accountInfo = ThirdAppModel::getUserInfoByUserId($uid);
        $cardNum = $accountInfo->card_num;
        //已开通名片数量
        $useNum = ThirdAppModel::getCardNum($uid);
        $info=[];
        $info['workNum'] = $workNum['workuser_count'];
        $info['cardNum'] = $cardNum;
        $info['useNum'] = $useNum['workuser_count'];
        return $info;
    }

    /**
     * 获取账号状态
     * @param $uid
     * @return array
     */
    public function getAccountStatus($uid){
        $time=[];
        $result = ThirdAppModel::getUserAuthInfo($uid);
        $time['start'] = date('Y-m-d',$result->create_time);
        $time['end'] = date('Y-m-d',$result->end_time);
        $time['use'] = intval((time()-$result->create_time)/(24*3600));
        $time['all'] = intval(($result->end_time - $result->create_time)/(24*3600)) ;
        return $time;
    }

    /**
     * 获取用户数量统计
     * @param $uid
     * @return mixed
     */
    public function getUserNum($uid){
        $workUsers = ThirdAppModel::getWorkUser($uid)->visible(['workuser']);
        foreach ($workUsers->workuser as $workUser){
            $workUser->visible(['id']);
        }
        $array =  $workUsers->toArray();
        $result = array_column($array['workuser'],'id');
        foreach ($result as $value){
            $num = WorkUser::getNum($value)->visible(['users_count']);
            $user[$value] =$num ->users_count;
        }
        return array_sum($user);
    }

    /**
     * 获取用户信息
     * @param $uid
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public function getUserInfo($uid){
        $result = ThirdAppModel::getUserAuthInfo($uid);
        if (null != $result){
            $userInfo['app_id'] = $result->app_id;
            $userInfo['app_secret'] = $result->app_secret;
            $userInfo['name'] = $result->name;
            $userInfo['sub_name'] = $result->sub_name;
            $userInfo['address'] = $result->address;
            $userInfo['head_img'] = $result->head_img;
            $userInfo['web_info'] = $result->web_info;
            return $userInfo;
        }
        return $result;
    }
    /**
     * 更新用户细信息
     * @param $uid
     * @param $data
     * @return $this
     */
    public function updateUserInfo($uid,$data){
        $result =  ThirdAppModel::updateUserInfo($uid,$data);
        return $result;
    }
    /**
     * 添加子元素
     * @param $data
     * @return $this
     */
    public function addSubWebInfo($uid,$data){
        WebSubelement::deleteSubWeb($uid);
        $result = WebSubelement::addSubWeb($data);
        return $result;
    }

    /**
     * 获取企业微信用户授权应用信息
     * @param $w_id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public function getAgent($w_id){
        $agentInfo  = Work::getAgent($w_id);
        return $agentInfo;
    }

    /**
     * 获取企业微信用户授权应用信息
     * @param $w_id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public function getAgentInfo($wu_id){
        $agentInfo  = Work::getAgentInfo($wu_id);
        return $agentInfo;
    }

    /**
     * 获取小程序授权详情
     * @param $t_id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public function getMiniDetail($t_id){
        $mini = \app\api\model\Mini::getMiniDetails($t_id);
        return $mini;
    }
    /**
     * 获取当前应用类型信息
     * @param $agents
     * @return mixed
     */
    private function getAppType($agents){
        $array =[];
        foreach ($agents as $k=>$v){
          array_push($array,$v['type']);
        }
        return $array;
    }

    /**
     * 统计总数
     * @param $t_id
     * @param $type
     * @param $time
     * @return array
     */
    public function getData($t_id,$type,$num){
        if ($num != 'all'){
            $time = mktime(0,0,0,date('m'),date('d')-$num,date('Y'));//时间戳
        }elseif ($num =='all'){
            $time = time()-time();
        }
        $allNum =  ThirdAppModel::getAllUser($t_id,$time);//用户总数
        $allFollow = ThirdAppModel::getAllFollowUser($t_id,$time);//总跟进数
        $allOrder = \app\api\model\Order::getAllOrders($t_id,$time);//总订单数
        $allPrice = \app\api\model\Order::getAllPrice($t_id,$time);//总金额
        $allTalk = \app\api\model\Message::getAllUser($t_id,$time);//忠沟通用户数
        $behavior = new \app\api\model\Behavior();
        $allBrowse =  $behavior->getBrowseData($t_id,$type['browse'],$time);//总浏览数
        $allShares = $behavior->getBrowseData($t_id,$type['shares'],$time);//总转发数
        $allSave_phone = $behavior->getBrowseData($t_id,$type['save_phone'],$time);//总保存数
        $allPraise = $behavior->getBrowseData($t_id,$type['praise'],$time);//总点赞数
        $data[] = ['num'=>$allNum,'follow'=>$allFollow,'order'=>$allOrder,
                    'price'=>$allPrice,'talk'=>$allTalk,'browse'=>$allBrowse,
                    'shares'=>$allShares,'save'=>$allSave_phone,'praise'=>$allPraise];
        return $data;
    }

    /**
     * 获取个行为统计
     * @param $t_id
     * @param $type
     * @param $time
     * @return false|int|\PDOStatement|string|\think\Collection
     */
    public function getCountData($t_id,$type,$num){
        if (null != $num){
            $time = time()-$num*24*3600;
        }else{
            $time = time()-time();
        }
        $behavior = new \app\api\model\Behavior();
        switch ($type){
            case "user":
                $data = ThirdAppModel::getAllUserByTime($t_id,$time);
                break;
            case "follow":
                $data = ThirdAppModel::getAllFollowUserByTime($t_id,$time);
                break;
            case "browse":
                $data = $behavior->getBrowseDataByTime($t_id,'browse',$time);
                break;
            case "shares":
                $data = $behavior->getBrowseDataByTime($t_id,'shares',$time);
                break;
            case "save_phone":
                $data = $behavior->getBrowseDataByTime($t_id,'save_phone',$time);
                break;
            case "praise":
                $data = $behavior->getBrowseDataByTime($t_id,'praise',$time);
                break;
        }
        for ($i=0;$i<$num;$i++){
            $times[] = date('m-d',time()-($num-$i-1)*3600*24);
        }
        $result['info'] = $data;
        $result['time'] = $times;
        return $result;
    }



}